using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Data.Objects;
using Googler.DAL;

namespace Googler.BLL
{

    public class BindingAdapter<T> : BindingList<T> where T : class,new()
    {
        public string Tag { get; set; }


        ObjectSet<T> _dataList = null;
        DataContext _context;
        public event EventHandler<CancelEventArgs> EntityRemoving;

        public BindingAdapter(DataContext context, ObjectSet<T> list)
        {
            _dataList = list;
            _context = context;

            foreach (T data in list)
            {
                this.Items.Add(data);
            }
        }
        public ObjectSet<T> DataList
        {
            get
            {
                return _dataList;
            }
        }
        protected override void RemoveItem(int index)
        {

            if (this.Count < (index + 1))
                throw new IndexOutOfRangeException();

            T data = this[index];
            ObjectStateEntry objState;
            if (_context.ObjectStateManager.TryGetObjectStateEntry(data, out objState))
            {
                _context.DeleteObject(data);
            }
            if (this.EntityRemoving != null)
            {
                CancelEventArgs e = new CancelEventArgs(false);
                this.EntityRemoving(data, e);
                if (e.Cancel)
                    return;
            }
            
            base.RemoveItem(index);
        }

        protected override object AddNewCore()
        {
            T data = new T();
            this.Items.Add(data);
            _dataList.AddObject(data);

            return data;
        }

        protected override void OnAddingNew(AddingNewEventArgs e)
        {
            _dataList.AddObject((T)e.NewObject);
            base.OnAddingNew(e);
        }


    }

}
